<template>
  <div class="store-example">
    <el-card class="example-card">
      <template #header>
        <div class="card-header">
          <h3>Pinia Store 使用示例</h3>
        </div>
      </template>
      
      <!-- 用户信息展示 -->
      <div class="section">
        <h4>用户信息 (来自 UserStore)</h4>
        <div v-if="userStore.isLoggedIn" class="user-info">
          <p><strong>用户ID:</strong> {{ userStore.currentUser.id }}</p>
          <p><strong>用户名:</strong> {{ userStore.currentUser.username }}</p>
          <p><strong>姓名:</strong> {{ userStore.currentUser.name }}</p>
          <p><strong>角色:</strong> {{ userStore.currentUser.role }}</p>
          <p><strong>登录状态:</strong> {{ userStore.isLoggedIn ? '已登录' : '未登录' }}</p>
          
          <div class="role-indicators">
            <el-tag v-if="userStore.isAdmin" type="danger">管理员</el-tag>
            <el-tag v-if="userStore.isTeacher" type="success">教师</el-tag>
            <el-tag v-if="userStore.isStudent" type="primary">学生</el-tag>
          </div>
        </div>
        <div v-else class="no-user">
          <p>用户未登录</p>
        </div>
      </div>

      <!-- 权限信息展示 -->
      <div class="section">
        <h4>权限信息 (来自 PermissionStore)</h4>
        <div class="permission-info">
          <p><strong>用户权限数量:</strong> {{ userButtons.length }}</p>
          <p><strong>用户菜单数量:</strong> {{ userMenus.length }}</p>
          
          <!-- 权限检查示例 -->
          <div class="permission-examples">
            <h5>权限检查示例:</h5>
            <div class="permission-check">
              <span>用户管理权限:</span>
              <el-tag :type="hasPermission('user:add') ? 'success' : 'danger'">
                {{ hasPermission('user:add') ? '有权限' : '无权限' }}
              </el-tag>
            </div>
            <div class="permission-check">
              <span>角色管理权限:</span>
              <el-tag :type="hasPermission('role:edit') ? 'success' : 'danger'">
                {{ hasPermission('role:edit') ? '有权限' : '无权限' }}
              </el-tag>
            </div>
            <div class="permission-check">
              <span>课程管理权限:</span>
              <el-tag :type="hasPermission('course:add') ? 'success' : 'danger'">
                {{ hasPermission('course:add') ? '有权限' : '无权限' }}
              </el-tag>
            </div>
          </div>

          <!-- 权限列表 -->
          <div class="permission-list" v-if="userButtons.length > 0">
            <h5>用户权限列表:</h5>
            <div class="permissions">
              <el-tag
                v-for="permission in userButtons"
                :key="permission"
                size="small"
                class="permission-tag"
              >
                {{ permission }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- Store 操作示例 -->
      <div class="section">
        <h4>Store 操作示例</h4>
        <div class="actions">
          <el-button @click="refreshUserInfo" :loading="refreshing">
            刷新用户信息
          </el-button>
          <el-button @click="refreshPermissions" :loading="refreshingPermissions">
            刷新权限信息
          </el-button>
          <el-button @click="showStoreData" type="info">
            显示 Store 数据
          </el-button>
        </div>
      </div>

      <!-- 实时状态更新展示 -->
      <div class="section">
        <h4>响应式状态展示</h4>
        <p class="reactive-demo">
          当前时间: {{ currentTime }} 
          (每秒更新，展示 Vue 3 响应式)
        </p>
        <p class="reactive-demo">
          用户状态变化监听: {{ statusMessage }}
        </p>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../stores/user'
import { usePermissions } from '../stores/permission'
import { getUserInfo } from '../api/auth'

// 使用 Stores
const userStore = useUserStore()
const { userButtons, userMenus, hasPermission, refreshPermissions: refreshPerms } = usePermissions()

// 本地状态
const refreshing = ref(false)
const refreshingPermissions = ref(false)
const currentTime = ref(new Date().toLocaleTimeString())
const statusMessage = ref('监听中...')

// 定时器
let timeInterval = null

// 刷新用户信息
const refreshUserInfo = async () => {
  try {
    refreshing.value = true
    const response = await getUserInfo()
    userStore.saveUser(response.data)
    ElMessage.success('用户信息刷新成功')
  } catch (error) {
    console.error('刷新用户信息失败:', error)
    ElMessage.error('刷新用户信息失败')
  } finally {
    refreshing.value = false
  }
}

// 刷新权限信息
const refreshPermissions = async () => {
  try {
    refreshingPermissions.value = true
    await refreshPerms()
    ElMessage.success('权限信息刷新成功')
  } catch (error) {
    console.error('刷新权限失败:', error)
    ElMessage.error('刷新权限失败')
  } finally {
    refreshingPermissions.value = false
  }
}

// 显示 Store 数据
const showStoreData = () => {
  console.log('=== User Store 数据 ===')
  console.log('currentUser:', userStore.currentUser)
  console.log('isLoggedIn:', userStore.isLoggedIn)
  console.log('isAdmin:', userStore.isAdmin)
  console.log('isTeacher:', userStore.isTeacher)
  console.log('isStudent:', userStore.isStudent)
  
  console.log('=== Permission Store 数据 ===')
  console.log('userButtons:', userButtons.value)
  console.log('userMenus:', userMenus.value)
  
  ElMessage.info('Store 数据已输出到控制台')
}

// 监听用户状态变化
watch(
  () => userStore.isLoggedIn,
  (newVal, oldVal) => {
    statusMessage.value = `登录状态从 ${oldVal ? '已登录' : '未登录'} 变为 ${newVal ? '已登录' : '未登录'}`
  },
  { immediate: true }
)

// 监听用户角色变化
watch(
  () => userStore.currentUser.role,
  (newRole) => {
    if (newRole) {
      statusMessage.value = `用户角色变更为: ${newRole}`
    }
  }
)

// 生命周期
onMounted(() => {
  // 启动时间更新定时器
  timeInterval = setInterval(() => {
    currentTime.value = new Date().toLocaleTimeString()
  }, 1000)
  
  statusMessage.value = '组件已挂载，开始监听状态变化'
})

onUnmounted(() => {
  // 清理定时器
  if (timeInterval) {
    clearInterval(timeInterval)
  }
})
</script>

<style scoped>
.store-example {
  padding: 20px;
}

.example-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header h3 {
  margin: 0;
  color: #333;
}

.section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.section h4 {
  color: #409eff;
  margin-bottom: 15px;
  font-size: 16px;
}

.section h5 {
  color: #666;
  margin: 15px 0 10px 0;
  font-size: 14px;
}

.user-info p {
  margin: 8px 0;
  color: #333;
}

.role-indicators {
  margin-top: 15px;
}

.role-indicators .el-tag {
  margin-right: 10px;
}

.no-user {
  color: #999;
  font-style: italic;
}

.permission-info p {
  margin: 8px 0;
  color: #333;
}

.permission-examples {
  margin: 15px 0;
}

.permission-check {
  display: flex;
  align-items: center;
  margin: 10px 0;
}

.permission-check span {
  margin-right: 10px;
  min-width: 120px;
  color: #666;
}

.permission-list {
  margin-top: 15px;
}

.permissions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
}

.permission-tag {
  font-size: 12px;
}

.actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.reactive-demo {
  padding: 10px;
  background-color: #f8f9fa;
  border-left: 4px solid #409eff;
  margin: 10px 0;
  color: #333;
  font-family: 'Courier New', monospace;
}
</style> 